#!/bin/bash
#
# Copyright (C) 2013 Christian Babeux <christian.babeux@efficios.com>
#
# SPDX-License-Identifier: GPL-2.0-only
#

TEST_DESC="Kernel tracer - Basic event"

CURDIR=$(dirname $0)/
TESTDIR=$CURDIR/../..
NUM_TESTS=21

TESTCMD="/bin/true"

source $TESTDIR/utils/utils.sh

function test_event_basic()
{
	TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
	SESSION_NAME="kernel_event_basic"

	create_lttng_session_ok $SESSION_NAME $TRACE_PATH

	lttng_enable_kernel_event $SESSION_NAME "sched_switch"
	lttng_enable_kernel_event $SESSION_NAME "sched_process_exit"
	lttng_enable_kernel_event $SESSION_NAME "sched_process_fork"

	start_lttng_tracing_ok

	# Running a process and waiting for its completion forces the triggering of
	# fork, sched_switch and exit events
	eval ${TESTCMD}
	stop_lttng_tracing_ok

	validate_trace_path_kernel "$TRACE_PATH" ""
	validate_trace "sched_switch" $TRACE_PATH
	validate_trace "sched_process_exit" $TRACE_PATH
	validate_trace "sched_process_fork" $TRACE_PATH

	destroy_lttng_session_ok $SESSION_NAME

	rm -rf $TRACE_PATH
}

function test_enable_after_start()
{
	TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
	SESSION_NAME="kernel_enable_after_start"

	create_lttng_session_ok $SESSION_NAME $TRACE_PATH

	lttng_enable_kernel_event $SESSION_NAME "sched_switch"

	start_lttng_tracing_ok
	lttng_enable_kernel_event $SESSION_NAME "sched_process_exit"

	# Running a process and waiting for its completion forces the triggering of
	# sched_switch and exit events
	eval ${TESTCMD}
	stop_lttng_tracing_ok

	validate_trace "sched_switch" $TRACE_PATH
	validate_trace "sched_process_exit" $TRACE_PATH

	destroy_lttng_session_ok $SESSION_NAME

	rm -rf $TRACE_PATH
}

# MUST set TESTDIR before calling those functions
plan_tests $NUM_TESTS

print_test_banner "$TEST_DESC"

check_skip_kernel_test $NUM_TESTS "Skipping all tests." ||
{
	validate_lttng_modules_present
	start_lttng_sessiond

	test_event_basic
	test_enable_after_start

	stop_lttng_sessiond
}
